<?php

namespace App\Console\Commands;

use App\Events\PostSaved;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class qcs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'qcs';

    const SESSION_PREFIX = 'session_id=';

    protected $initArr = [
        'lmk' => 'session_id=2RI4SN0FN4RHNAO0QA0HP2V2FQ',//大号
        'sg' => 'session_id=1OD0EM3JD537PTSGNDNK4F738V',//时光
        'laoma' => 'session_id=2BAESPQ9RG69OI732DQ2G11RTJ',//7522
        'lm' => 'session_id=2BAESPQ9RG69OI732DQ2G11RTJ',//青青小号
        'lqq' => 'session_id=2BAESPQ9RG69OI732DQ2G11RTJ',//青青号
    ];

    protected $userName;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '屈臣氏';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //是否只查询申请成功的列表
        $isGetSuccessList = 0;
        $user_arr = ['lmk', 'sg', 'laoma', 'lm', 'lqq'];


        foreach ($user_arr as $v) {
            $this->userName = $v;

            //判断登录
            $userinfo = $this->login();


            dump($userinfo);
            //设置cookie
            $this->initArr[$this->userName] = self::SESSION_PREFIX . json_decode($userinfo, 1)['data']['sessionId'];

            //获取申请成功的列表
            $this->http_get_sign_success();

            //获取待申请物品列表
            $list = $this->getFreeList();

            //开始申请
            if (!$isGetSuccessList) {
                foreach ($list as $v) {
                    list($params, $length) = $this->getParams($v['id'], $v['title']);

                    dump($params);

                    $header = $this->getHeader($length);

                    $res = $this->curl_post($params, $header);
                    dump($res);

                    json_decode($res, 1)['code'] != 200 && Log::info($v['title'] . '申请失败----' . $res);

                    sleep(rand(5,10));
                }
            }
        }

    }

    //检查用户是否登录


    public function login()
    {
        if ($this->userName == 'lmk') {
            $params = '{"nickName":"别抢我的塑料袋","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/YTto8utQm7pCWiaibLCWK9t7zzFV2S4wdia4uLBFxhkPUoUzBUngOCJOzRC9pvsX4uGzpPuFGicCyc4ow2fpKEQNIA/132","unionId":"E29FBDE497323007F4C75518014B7CBECA47C39477A06971EB30EF986D5779FB","openId":"BC4115CFE1C1BBF860AD9C06E10B8E2BB63E1DE117538609B3F50BACE9665675"}';
        } elseif ($this->userName == 'sg') {
            $params = '{"nickName":"时光","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIsdBPvqH0AoDGcgFC0pvSJAAdbGezvHSl3gibicHFiauw6NYnsaUWucAlGCO2EJrUvC67Z6GrnrVqSg/132","unionId":"5A53611964AA67671D4EADDF87F155A8FA796BC303D1A70330D28D76A1EBE44C","openId":"B078F716796332126C2299314ED03EE1C07566E033C2253149E6698E205DE0D1"}';
        } elseif ($this->userName == 'laoma') {
            $params = '{"nickName":"我不是猫咪","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/cgSrWw1hB5Tz6yulOXjfJULQYpTzMIP12kwSlFWMSxZiaUWJXdZZgMulIw2EkYFeaj8R1m1RB93A21huKQbPEXA/132","unionId":"B8F182A5B0437997A4488B8C04F6347EDB3642D50A83C79D72769ABC3FD03B3E","openId":"98E834D8454ABB7F828F0DF91E104565F9FF447181BFFFD508EA2259AA4822AC"}';
        } elseif ($this->userName == 'lm') {
            $params = '{"nickName":"红豆","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/f2IWPFzynCxOA3GVxs3704mnQJeXRpJeNyLNDI3rWERiaBn9fyB03P1PBcFWMoeduBqibq7rIZ8VaHanUaGplr5g/132","unionId":"B12A2378B5FC51AFEBFD0E0A11A6F959ECB1EB34FDFD0BA9BAFBCE760B329BB6","openId":"19B498E2ABA95ADD66F80EBF7FB14E535B350A1DA4F11B6013352FA517BDB20F"}';
        } elseif ($this->userName == 'lqq') {
            $params = '{"nickName":"SHMILY","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTI4MmFsor5MUicBMLtKqEOwWU5BIdExAPBeXC9iaVkMrwwPWtWMbMSTrMduJkPAGn6rv7QYRh7R0FwA/132","unionId":"D2286CFD39C22AAC7C4881C82DA9849849E034FE03FFA7D39F77ED98E6B666CE","openId":"7AD97053233F846D91BCFAE7AEF8C639298B2CCAA4E89068BD5D5068557F5589"}';
        }


        $header = $this->getLoginHeader(strlen($params));

        return $this->curl_post($params, $header, 'https://zdm.omni.watsonsestore.com.cn/hwb_gw/hwb-api/v3/login');


    }


    public function getLoginHeader($lenth)
    {
        return [
            'Host:  zdm.omni.watsonsestore.com.cn',
            'Connection:  keep-alive',
            'Content-Length:  ' . $lenth,
            'User-Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
            'X-WECHAT-HOSTSIGN:  {"noncestr":"2fcb0b42a2fb44884777cf42fd76a677","timestamp":' . time() . ',"signature":"deeac5b220adcb98d4cff6474dd53d9a1636e4a2"}',
            'content-type:  application/json',
            'Referer:  https://servicewechat.com/wx1ffbd6927043dff7/392/page-frame.html',
            'Accept-Encoding:  gzip, deflate, br',
        ];
    }


    public function getParams($goods_id, $desc)
    {
        $desc = '产品';
        if ($this->userName == 'lmk') {
            $params = '{"userName":"李孟凯","address":"淞泽家园七区38幢102","phoneNumber":"18238647889","countyName":"苏州工业园区","cityName":"苏州市","provinceName":"江苏省","greenCode":"","declaration":"作为一个老用户,希望能申请到这款' . $desc . '，感谢工作人员的付出，支持屈臣氏！","postalCode":51000,"focusSkinQs":"undefined","interested":"undefined","userId":7037139,"trialId":"' . $goods_id . '","vipApplyType":0,"sourceType":1,"primeApplyType":0}';
        } elseif ($this->userName == 'sg') {
            $params = '{"userName":"时光","address":"淞泽家园七区淞泽家园7区","phoneNumber":"15560174484","countyName":"苏州工业园区","cityName":"苏州市","provinceName":"江苏省","greenCode":"","declaration":"希望能申请到这款' . $desc . ',感谢工作人员的付出，支持屈臣氏！","postalCode":51000,"focusSkinQs":"undefined","interested":"undefined","userId":11514889,"trialId":"' . $goods_id . '","vipApplyType":0,"sourceType":1,"primeApplyType":0}';
        } elseif ($this->userName == 'laoma') {
            $params = '{"userName":"陈彩霞","address":"裴村营村村里的快递点自提","phoneNumber":"18224561013","countyName":"辉县市","cityName":"新乡市","provinceName":"河南省","greenCode":"","declaration":"希望能申请试用这款' . $desc . ',感谢工作人员的付出，支持屈臣氏！","postalCode":453600,"focusSkinQs":"undefined","interested":"undefined","userId":11515305,"trialId":"' . $goods_id . '","vipApplyType":0,"sourceType":1,"primeApplyType":0}';
        } elseif ($this->userName == 'lm') {
            $params = '{"userName":"李木","address":"淞泽家园七区七区快递自提点","phoneNumber":"17621636385","countyName":"苏州工业园区","cityName":"苏州市","provinceName":"江苏省","greenCode":"","declaration":"屈臣氏的试用还是可以的，希望这次能够申请到这款' . $desc . ',感谢工作人员的付出，支持屈臣氏！","postalCode":51000,"focusSkinQs":"undefined","interested":"undefined","userId":11655773,"trialId":"' . $goods_id . '","vipApplyType":0,"sourceType":1,"primeApplyType":0}';
        } else {
            $params = '{"userName":"李木","address":"CCB建融家园17号楼","phoneNumber":"18238473351","countyName":"浦东新区","cityName":"上海市","provinceName":"上海","greenCode":"","declaration":"希望能申请到这款' . $desc . ',感谢工作人员的付出，支持屈臣氏！","postalCode":51000,"focusSkinQs":"undefined","interested":"undefined","userId":11656090,"trialId":"' . $goods_id . '","vipApplyType":0,"sourceType":1,"primeApplyType":0}';
        }

        return [$params, strlen($params)];
    }

    /**
     * 获取试用列表
     */
    public function getFreeList()
    {

        $json = $this->http_get();

        $data = json_decode($json, 1)['data']['resultList'];


        $data = array_filter($data, function ($v) {
            if ($v['applyStatus'] == 1) {
                return false;
            }
            return true;
        });

        $data = array_map(function ($val) {
            return [
                'id' => $val['id'],
                'title' => $val['title'],
            ];
        }, $data);

        return $data;

    }

    public function getHeader($lenth)
    {
        return [
            'Host:  zdm.omni.watsonsestore.com.cn',
            'Connection:  keep-alive',
            'Content-Length:  ' . $lenth,
            'User-Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
            'X-WECHAT-HOSTSIGN:  {"noncestr":"3e40a95b8cbf4aba30e5c9a6826a76f5","timestamp":1650543972,"signature":"d83601d1911df01ec55f63d3823dcd7a768de245"}',
            'content-type:  application/json',
            'cookie:  ' . $this->initArr[$this->userName],
            'Referer:  https://servicewechat.com/wx1ffbd6927043dff7/392/page-frame.html',
            'Accept-Encoding:  gzip, deflate, br'
        ];
    }


    function curl_post($param, $headers = [], $url = 'https://zdm.omni.watsonsestore.com.cn/hwb_gw/trial-api/trial/user/apply')
    {

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $param,
            CURLOPT_HTTPHEADER => $headers,
        ));

        $response = curl_exec($curl);

        curl_close($curl);

        return $response;
    }

    /**
     * 获取试用列表
     * @return bool|string
     */
    function http_get()
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://zdm.omni.watsonsestore.com.cn/hwb_gw/trial-api/trial/trials?trialType=going&pageNo=1&pageSize=100&indexFlag=true',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Host:  zdm.omni.watsonsestore.com.cn',
                'Connection:  keep-alive',
                'User-Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
                'X-WECHAT-HOSTSIGN:  {"noncestr":"d66e571f8d88ba00487da9cb058f2d9b","timestamp":' . time() . ',"signature":"685c241864919aa41b9d20de35d62cee466958b0"}',
                'content-type:  application/json',
                'cookie:  ' . $this->initArr[$this->userName],
                'Referer:  https://servicewechat.com/wx1ffbd6927043dff7/392/page-frame.html',
                'Accept-Encoding:  gzip, deflate, br'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }


    /**
     * 测试代理
     * @return bool|string
     */
    function http_get_daili()
    {
        $curl = curl_init();
//        curl_setopt($ch, , ); //
//        curl_setopt($ch, CURLOPT_PROXY, "112.65.219.72"); //代理服务器地址
//        curl_setopt($ch, , 80); //代理服务器端口
////curl_setopt($ch, CURLOPT_PROXYUSERPWD, ":"); //http代理认证帐号，username:password的格式
//        curl_setopt($ch, , ); //使用http代理模式
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://httpbin.org/ip',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_PROXYAUTH => CURLAUTH_BASIC,//代理认证模式
            CURLOPT_PROXY => '187.115.10.50',//代理认证模式
            CURLOPT_PROXYPORT => 20183,//代理认证模式
            CURLOPT_PROXYTYPE => CURLPROXY_HTTP,//代理认证模式
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Connection:  keep-alive',
                'User-Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
                'content-type:  application/json',
                'Accept-Encoding:  gzip, deflate, br'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }

    /**
     * 获取试用成功列表
     * @return bool|string
     */
    function http_get_sign_success()
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://zdm.omni.watsonsestore.com.cn/hwb_gw/trial-api/trial/user/my-trial/page?userId=11655773&pageSize=10&pageNo=1&applyStatus=2&timestamp=1650979187539',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Host:  zdm.omni.watsonsestore.com.cn',
                'Connection:  keep-alive',
                'User-Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
                'X-WECHAT-HOSTSIGN:  {"noncestr":"d66e571f8d88ba00487da9cb058f2d9b","timestamp":' . time() . ',"signature":"685c241864919aa41b9d20de35d62cee466958b0"}',
                'content-type:  application/json',
                'cookie:  ' . $this->initArr[$this->userName],
                'Referer:  https://servicewechat.com/wx1ffbd6927043dff7/393/page-frame.html',
                'Accept-Encoding:  gzip, deflate, br'
            ),
        ));

        $response = curl_exec($curl);
        $response = json_decode($response, true);

        $res = $response['data']['resultList'] ?? [];

        $arr = array_map(function ($val) {
            return [
                'title' => $val['title'] ?? '',
                'trackingNumber' => $val['detailInfo']['trackingNumber'] ?? ''
            ];
        }, $res);


        //写入Log
        Log::info($this->userName . '试用成功列表', $arr);
    }
}
